package com.my.study.globalfilter.normal;

import com.my.study.aop.annotation.FilterType;
import com.my.study.enums.ApiTypeEnum;
import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.util.HttpGlobalUtil;
import com.my.study.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    @FilterType(type = ApiTypeEnum.NORMAL_API)
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // token校验
        String token = request.getHeaders().getFirst("Authorization");
        //token是否存在
        if (token == null) {
            return HttpGlobalUtil.fail(exchange.getResponse(), BusinessExceptionEnum.PERMISSION.code);
        }
        //验证token是否有效
        boolean result = JwtUtil.checkToken(token);
        if (!result) {//无效
            return HttpGlobalUtil.fail(exchange.getResponse(), BusinessExceptionEnum.PERMISSION.code);
        } else {//有效令牌则刷新
            String refreshToken = JwtUtil.refreshToken(token);
            exchange.getRequest().mutate().headers(httpHeaders -> {
                httpHeaders.add("Authorization",refreshToken);
            });
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
